﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MovieCollectionManager.DataModel;
using System.IO;

namespace MovieCollectionManager
{
    public partial class ListForm : Form
    {
        public ListForm()
        {
            InitializeComponent();
        }

        private void ListForm_Load(object sender, EventArgs e)
        {
            using (var db = new MovieCollectionConteiner())
            {
                List<Movie> movies = db.Movies.ToList();
                listBoxMovieList.DataSource = movies;
                listBoxMovieList.DisplayMember = "Title";
                listBoxMovieList.ValueMember = "Id";
                textBoxMoviesCount.Text = movies.Count.ToString();
            }
        }

        private void listBoxMovieList_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = listBoxMovieList.SelectedIndex;
            ChangeMovieInfo(selectedIndex);
        }

        private void ChangeMovieInfo(int index)
        {
            Movie selectedMovie = (Movie)listBoxMovieList.Items[index];
            textBoxTitle.Text = selectedMovie.Title;
            textBoxRate.Text = selectedMovie.Rate.ToString();
            textBoxType.Text = selectedMovie.Type.ToString();
            textBoxReleaseDate.Text = selectedMovie.ReleaseDate.ToString();
            textBoxLength.Text = selectedMovie.Length.ToString();
            textBoxDescription.Text = selectedMovie.Description;
            checkBoxLent.Checked = selectedMovie.Lent;

            if (selectedMovie.BoxArt.Count() == 0)
            {
                pictureBoxArt.Image = null;
                return;
            }

            SetPictureBoxImage(selectedMovie);
        }

        private void SetPictureBoxImage(Movie selectedMovie)
        {
            byte[] imagemEmBytes = selectedMovie.BoxArt;
            MemoryStream memoryStream = new MemoryStream(imagemEmBytes, 0, imagemEmBytes.Length);
            memoryStream.Write(imagemEmBytes, 0, imagemEmBytes.Length);

            pictureBoxArt.Image = Image.FromStream(memoryStream, true);
            memoryStream.Close();
        }

        private void buttonBack_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void pictureBoxArt_Click(object sender, EventArgs e)
        {
            FullSizedImageForm fullSizedImageForm = new FullSizedImageForm(pictureBoxArt.Image);
            fullSizedImageForm.ShowDialog();
        }
    }
}
